import 'dart:io';
import 'package:furaha_mkopo/commonTool/fm_system_auth_manager.dart';
import 'package:image_picker/image_picker.dart';

class FMImagePickerManager {
  final FMSystemAuthManager _authManager = FMSystemAuthManager();
  final ImagePicker _imagePicker = ImagePicker();

  /// 打开相机或相册获取图片
  /// 参数说明：
  /// - source: ImageSource.camera（相机） 或 ImageSource.gallery（相册）
  /// 返回值：File? 类型（用户取消选择或失败时返回 null）
  Future<File?> pickImage(ImageSource source,{CameraDevice preferredCameraDevice = CameraDevice.rear}) async {
    try {
      // 检查权限（相机或相册）
      bool hasPermission = await _checkPermission(source);
      if (!hasPermission) return null;

      // 执行图片选择
      final XFile? image = await _imagePicker.pickImage(
        source: source,
        preferredCameraDevice: preferredCameraDevice,
        maxWidth: 1800, // 限制图片宽度
        maxHeight: 1800, // 限制图片高度
        imageQuality: 85, // 压缩质量 (0-100)
      );

      return image != null ? File(image.path) : null;
    } catch (e) {
      print('Image picker error: $e');
      return null;
    }
  }

  /// 权限检查与请求
  Future<bool> _checkPermission(ImageSource source) async {
    bool hasPermission = false;

    if (source == ImageSource.camera) {
      // 相机权限检查
      hasPermission = await _authManager.checkCameraPermission();
      if (!hasPermission) {
        await _authManager.requestCameraPermission();
        hasPermission = await _authManager.checkCameraPermission();
      }
    } else {
      // 相册权限检查
      hasPermission = await _authManager.checkGalleryPermission();
      if (!hasPermission) {
        await _authManager.requestGalleryPermission();
        hasPermission = await _authManager.checkGalleryPermission();
      }
    }

    return hasPermission;
  }
}